package com.gxa.interceptor;

import com.gxa.exception.GlobalException;
import com.gxa.pojo.entity.system.User;
import com.gxa.utils.JwtUtils;
import com.gxa.utils.MessageCode;
import com.gxa.utils.UserThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author lch
 * @Date 2024/2/22 15:14
 * @Description 拦截器，验证token
 **/
public class AuthorizeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.放行探测请求
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }

        //2.获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            //从参数中再获取一次token
            token = request.getParameter("token");
            if (token == null || token.isEmpty()) {
                //没有登录，抛出异常(未携带token)
//                return true;
//                return true; //TODO
                throw new GlobalException(MessageCode.NOT_EXISTS_TOKEN);
            }
        }

        //3.验证token是否有效
        boolean result = JwtUtils.verify(token);
        if (!result) {
            //无效的token
//            return true;
//            return true;
            //TODO
            throw new GlobalException(MessageCode.INVALID_TOKEN);
        }

        //4.验证通过，解析token，并把用户信息保存到本地线程中
        User user = JwtUtils.parse(token);
        UserThreadLocal.setUser(user);
        return true;
    }
}
